/*
 * LogSelector.java
 *
 * Created on August 26, 2008, 10:03 AM
 */
package com.lct.eq2.gui;

import java.awt.Toolkit;
import java.io.File;
import java.util.ArrayList;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JComboBox;
import javax.swing.JFileChooser;
import javax.swing.JLabel;

/**
 *
 * @author  waite
 */
public class LogSelector extends javax.swing.JFrame {

    private File[] servers;
    private LiteGui parentGui;
    private File serverDir;
    private SearchHelper helper;

    /** Creates new form LogSelector */
    public LogSelector(LiteGui parentGui) {
        this.setIconImage(Toolkit.getDefaultToolkit().getImage("eq2.png"));
        this.parentGui = parentGui;
        initComponents();
        this.jComboBox1.setEnabled(false);
        this.jComboBox2.setEnabled(false);
        this.jLabel1.setEnabled(false);
        this.jLabel2.setEnabled(false);
        this.jLabel4.setText("");
    }

    public boolean isWindows() {
        String os = System.getProperty("os.name").toLowerCase();
        //windows
        return (os.indexOf("win") >= 0);
    }

    public boolean isUnix() {
        String os = System.getProperty("os.name").toLowerCase();
        //linux or unix
        return (os.indexOf("nix") >= 0 || os.indexOf("nux") >= 0);
    }

    /**
     * Nested Class
     */
    class SearchHelper extends Thread {

        private boolean manual;
        private String manualPath;
        LogSelector parent;
        private boolean running = true;

        public SearchHelper(LogSelector parent, boolean manual) {
            this.parent = parent;
            this.manual = manual;
        }

        public void setManualPath(String path) {
            this.manualPath = path;
        }

        public void stopRunning() {
            this.running = false;
        }

        @Override
        public void run() {
//            System.out.println(this.isWindows());
            if (!manual && this.parent.isWindows()) {
                this.parent.jButton1.setText("Cancel Automatic Search");
                this.parent.jButton1.setEnabled(true);

                File c = new File("C:\\");
                File d = new File("D:\\");
                File e = new File("E:\\");
                File f = new File("F:\\");
                File g = new File("G:\\");

                ArrayList hdds = new ArrayList();
                hdds.add(c);
                hdds.add(d);
                hdds.add(e);
                hdds.add(f);
                hdds.add(g);

                try {
                    for (int i = 0; i < hdds.size(); i++) {
                        File file = (File) hdds.get(i);
                        //System.out.println(i + " " + file.isDirectory());
                        if (file.isDirectory()) {
                            File[] files = file.listFiles();
                            int x = 0;
                            while (running && x < files.length) {
//                            for (int x = 0; x < files.length; x++) {
                                File _file = files[x];
                                if (_file.isDirectory()) {
                                    //System.out.println(_file.getAbsolutePath());
                                    try {
                                        serverDir = searchForEQ2(_file, 0);
//                                        System.out.println(serverDir);
                                    } catch (Exception exc) {
                                        exc.printStackTrace();
                                        //nothing
                                    }
                                    if (serverDir != null) {
                                        serverDir = new File(serverDir.getAbsolutePath() + File.separator + "logs");
                                        break;
                                    } else {
                                        //break;
                                    }
                                }
                                x++;
                            }
                        }
                    }
                } catch (Exception ex) {
                    // nothing
                    ex.printStackTrace();
                }
            } else {
                serverDir = new File(this.manualPath + File.separator + "logs");
            }

            if (serverDir != null) {
                servers = serverDir.listFiles();
                if (servers != null) {
                    for (int x = 0; x < servers.length; x++) {
                        File server = servers[x];
                        if (server.isDirectory()) {
                            this.parent.addToComboBox(this.parent.jComboBox1, server.getName());
                        }
                    }
                    this.parent.jLabel3.setText("Status: EQ2 Found.");
                    this.parent.enableComboBox(this.parent.jComboBox1);
                    this.parent.enableComboBox(this.parent.jComboBox2);
                    this.parent.enableLabel(this.parent.jLabel1);
                    this.parent.enableLabel(this.parent.jLabel2);
                    this.parent.jLabel4.setText("");
                    this.parent.jButton1.setText("Select");
                    this.parent.jButton1.setEnabled(true);
                } else {
                    this.parent.jLabel3.setText("Status: Could not locate EQ2!");
                    this.parent.jLabel4.setText("Please manually select EQ2's install dir.");
                    this.parent.jButton1.setText("Select EQ2 Install Directory");
                    this.parent.jButton1.setEnabled(true);
                }
            } else {
                this.parent.jLabel3.setText("Status: Could not locate EQ2!");
                this.parent.jLabel4.setText("Please manually select EQ2's install dir.");
                this.parent.jButton1.setText("Select EQ2 Install Directory");
                this.parent.jButton1.setEnabled(true);
            }
        }
    };

    public void searchForLog(boolean manual, String manualPath) {
        helper = new SearchHelper(this, manual);
        if (manual) {
            helper.setManualPath(manualPath);
        }
        helper.start();
    }

    public void addToComboBox(JComboBox box, Object data) {
        DefaultComboBoxModel model = (DefaultComboBoxModel) box.getModel();
        model.addElement(data);
    }

    public void enableLabel(JLabel label) {
        label.setEnabled(true);
    }

    public void enableComboBox(JComboBox box) {
        box.setEnabled(true);
    }

    private static File searchForEQ2(File fdir, int depth) {
        int MAX_DEPTH = 2;
        File rval = null;
        if (fdir.isDirectory() && depth < MAX_DEPTH) {
            String path = fdir.getAbsolutePath().toLowerCase();
            if (path.contains("everquest 2") || path.contains("everquest II")) {
                rval = fdir;
                return rval;
            }
            try {
                for (File f : fdir.listFiles()) {  // Go over each file/subdirectory.
                    path = f.getAbsolutePath().toLowerCase();
                    if (f.isDirectory() && (path.contains("everquest 2") || path.contains("everquest II"))) {
                        rval = f;
                        return rval;
                    } else {
                        rval = searchForEQ2(f, depth + 1);
                        if (rval != null) {
                            return rval;
                        }
                    }
                }
            } catch (NullPointerException ex) {
                //nothing
            }
        }

        return rval;
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jComboBox1 = new javax.swing.JComboBox();
        jLabel1 = new javax.swing.JLabel();
        jComboBox2 = new javax.swing.JComboBox();
        jLabel2 = new javax.swing.JLabel();
        jButton1 = new javax.swing.JButton();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Log Selection");
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowClosed(java.awt.event.WindowEvent evt) {
                formWindowClosed(evt);
            }
            public void windowClosing(java.awt.event.WindowEvent evt) {
                formWindowClosing(evt);
            }
        });

        jComboBox1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jComboBox1ActionPerformed(evt);
            }
        });

        jLabel1.setText("Select the Server You Play On:");

        jLabel2.setText("Select Your Character:");

        jButton1.setText("Select");
        jButton1.setEnabled(false);
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jLabel3.setText("Status: Searching for EQ2. Please wait...");

        jLabel4.setText("S");

        org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(org.jdesktop.layout.GroupLayout.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING)
                    .add(jLabel4, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 202, Short.MAX_VALUE)
                    .add(org.jdesktop.layout.GroupLayout.LEADING, jComboBox1, 0, 202, Short.MAX_VALUE)
                    .add(org.jdesktop.layout.GroupLayout.LEADING, jLabel2, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 202, Short.MAX_VALUE)
                    .add(jComboBox2, 0, 202, Short.MAX_VALUE)
                    .add(org.jdesktop.layout.GroupLayout.LEADING, jLabel1)
                    .add(org.jdesktop.layout.GroupLayout.LEADING, jLabel3)
                    .add(org.jdesktop.layout.GroupLayout.LEADING, layout.createSequentialGroup()
                        .add(10, 10, 10)
                        .add(jButton1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 181, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(layout.createSequentialGroup()
                .addContainerGap()
                .add(jLabel3)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(jLabel4)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(jLabel1)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(jComboBox1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(jLabel2)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(jComboBox2, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.UNRELATED)
                .add(jButton1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 23, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents
    private void jComboBox1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jComboBox1ActionPerformed
        DefaultComboBoxModel model = (DefaultComboBoxModel) jComboBox1.getModel();
        String serverName = model.getSelectedItem().toString();

        for (int x = 0; x < servers.length; x++) {
            File server = servers[x];
            if (server.isDirectory()) {
                if (server.getName().equalsIgnoreCase(serverName)) {
                    DefaultComboBoxModel model2 = (DefaultComboBoxModel) jComboBox2.getModel();
                    model2.removeAllElements();
                    File[] characters = server.listFiles();
                    for (int y = 0; y < characters.length; y++) {
                        File character = characters[y];
                        if (!character.isDirectory()) {
                            if (!character.getName().contains("^M")) {
                                String tmp = character.getName();
                                model2.addElement(tmp.substring(tmp.indexOf("_") + 1, tmp.lastIndexOf(".")));
                            }
                        }
                    }
                    break;
                }
            }
        }
    }//GEN-LAST:event_jComboBox1ActionPerformed

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        if (jButton1.getText().equalsIgnoreCase("Select")) {
            this.jButton1.setEnabled(false);
            this.jLabel3.setText("Status: Updating character...");
            DefaultComboBoxModel model = (DefaultComboBoxModel) jComboBox1.getModel();
            DefaultComboBoxModel model2 = (DefaultComboBoxModel) jComboBox2.getModel();

            String logLocation = serverDir.getAbsolutePath() + File.separator + model.getSelectedItem() + File.separator + "eq2log_" + model2.getSelectedItem() + ".txt";
            this.parentGui.updateLogPath(new File(logLocation));
            this.dispose();
        } else if (jButton1.getText().equalsIgnoreCase("Select EQ2 Install Directory")) {
            //this.setVisible(false);
            //this.parentGui.manuallySelectLogFile();
            JFileChooser jFileChooser = new JFileChooser();
            jFileChooser.setDialogTitle("Select Where EQ2 is Installed");
            
//            jFileChooser.setCurrentDirectory(new File("C:\\"));
            jFileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
            jFileChooser.setAcceptAllFileFilterUsed(false);
            int returnVal = jFileChooser.showOpenDialog(this);

            if (returnVal == JFileChooser.APPROVE_OPTION) {
                File file = jFileChooser.getSelectedFile();
                this.searchForLog(true, file.getAbsolutePath());
            }
            //this.dispose();
        } else {
        }
    }//GEN-LAST:event_jButton1ActionPerformed

    private void formWindowClosed(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosed
    }//GEN-LAST:event_formWindowClosed

    private void formWindowClosing(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosing
    }//GEN-LAST:event_formWindowClosing
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton1;
    private javax.swing.JComboBox jComboBox1;
    private javax.swing.JComboBox jComboBox2;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    // End of variables declaration//GEN-END:variables
}
